/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */

import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
  DefaultFooter,
} from '@ant-design/pro-layout';
import React, { useEffect } from 'react';
import Link from 'umi/link';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import { Icon, Result, Button } from 'antd';

import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { ConnectState } from '@/models/connect';
import { isAntDesignPro, getAuthorityFromRouter } from '@/utils/utils';
import logo from '../assets/logo.svg';
import { MenuItem } from '@/models/menu';
import Tabs from 'antd/es/tabs';

const TabPane = Tabs.TabPane;
import styles from './BasicLayout.less';

const noMatch = (
  <Result
    status="403"
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
  menuList: Array<MenuItem>;
}

export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};

const convertMenu = (menuList: MenuItem[]): MenuDataItem[] => {
  // id:0, menuName:'首页',routerUrl:'/index',menuIcon:'fa-book',children:null,affix:true,hidden:true
  if (menuList) {
    menuList = menuList.filter((item: any) => {
      return item.type === 0 || item.type === 1;
    });

    const resMenuList = menuList.map((item: any) => {
      let childrenRes: any = [];
      if (item.children && item.children.length > 0) {
        childrenRes = convertMenu(item.children);
      }

      if (item.type === 0) {
        return {
          path: item.routerUrl,
          name: item.menuName,
          icon: item.menuIcon,
          children: childrenRes,
        };
      } else {
        return {
          path: item.routerUrl,
          name: item.menuName,
          children: childrenRes,
        };
      }
    });
    return resMenuList as MenuDataItem[];
  }
  return [];
};

/**
 * use Authorized check all menu item
 */
const menuDataRender = (menuList: MenuItem[]): MenuDataItem[] => convertMenu(menuList);

const defaultFooterDom = (
  <DefaultFooter
    copyright="2019 蚂蚁金服体验技术部出品"
    links={[
      {
        key: 'Ant Design Pro',
        title: 'Ant Design Pro',
        href: 'https://pro.ant.design',
        blankTarget: true,
      },
      {
        key: 'github',
        title: <Icon type="github" />,
        href: 'https://github.com/ant-design/ant-design-pro',
        blankTarget: true,
      },
      {
        key: 'Ant Design',
        title: 'Ant Design',
        href: 'https://ant.design',
        blankTarget: true,
      },
    ]}
  />
);

const footerRender: BasicLayoutProps['footerRender'] = () => {
  if (!isAntDesignPro()) {
    return defaultFooterDom;
  }
  return (
    <>
      {defaultFooterDom}
      <div
        style={{
          padding: '0px 24px 24px',
          textAlign: 'center',
        }}
      >
        <a href="https://www.netlify.com" target="_blank" rel="noopener noreferrer">
          <img
            src="https://www.netlify.com/img/global/badges/netlify-color-bg.svg"
            width="82px"
            alt="netlify logo"
          />
        </a>
      </div>
    </>
  );
};

const BasicLayout: React.FC<BasicLayoutProps> = props => {
  const { dispatch, children, settings, location = { pathname: '/' }, menuList } = props;
  /**
   * constructor
   */

  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'settings/getSetting',
      });

      let permissions: any = [];
      filterPermissions(menuList, permissions);
      dispatch({
        type: 'permission/addPermission',
        payload: permissions,
      });
    }
  }, []);

  const filterPermissions = (menus: any, permissions: any) => {
    menus.forEach((item: any) => {
      if (typeof item.permsCode === 'string') {
        item.permsCode = item.permsCode.trim();
      }
      if (item.permsCode) {
        permissions.push(item.permsCode);
      }
      if (item.children && item.children.length > 0) {
        filterPermissions(item.children, permissions);
      }
    });
  };

  /**
   * init variables
   */
  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };
  // get children authority
  const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/') || {
    authority: undefined,
  };

  return (
    <ProLayout
      logo={logo}
      onCollapse={handleMenuCollapse}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl) {
          return defaultDom;
        }
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }}
      footerRender={footerRender}
      menuDataRender={() => menuDataRender(menuList)}
      rightContentRender={rightProps => <RightContent {...rightProps} />}
      {...props}
      {...settings}
    >
      <div className={styles.menuTabs}>
        <Tabs hideAdd type="editable-card" defaultActiveKey="1" tabPosition="top">
          {[...Array(10).keys()].map(i => (
            <TabPane tab={`Tab-${i}`} key={i + ''}></TabPane>
          ))}
        </Tabs>
      </div>

      <Authorized authority={authorized!.authority} noMatch={noMatch}>
        {children}
      </Authorized>
    </ProLayout>
  );
};

export default connect(({ global, settings, menus }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
  menuList: menus.menuList,
}))(BasicLayout);
